package com.yinxing.framework.utils;

import java.util.concurrent.ThreadLocalRandom;

/**
 * 用来获取随机字符串的工具类
 * 随机范围(小写a-z|大写A-Z|数字0-9)
 */
public class RandomStringUtils {

    private static final char[] PRINTABLE_CHARACTERS =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345679".toCharArray();

    private static final char[] NUMBER_CHARACTERS = "0123456789".toCharArray();

    /**
     * 获取随机字符串(线程安全)
     * @param length 字符串长度
     * @return 范围(小写a-z|大写A-Z|数字0-9)
     */
    public static String getRandomString(int length) {
        final byte[] random = getRandomBytes(length);
        return convertBytesToString(random, PRINTABLE_CHARACTERS);
    }

    /**
     * 获取随机数字字符串(线程安全)
     * @param length 字符串长度
     * @return 范围(0-9)
     */
    public static String getRandomNumberString(int length) {
        final byte[] random = getRandomBytes(length);
        return convertBytesToString(random, NUMBER_CHARACTERS);
    }

    /**
     * 获取随机二进制数组(线程安全)
     * @param length 数组长度
     * @return 随机二进制数组 例如:[1,230,18,24]
     */
    private static byte[] getRandomBytes(int length) {
        final byte[] random = new byte[length];
        ThreadLocalRandom.current().nextBytes(random);
        return random;
    }

    /**
     * 把二进制数组转换为字符串
     * @param random 二进制数组
     * @return 字符串
     */
    private static String convertBytesToString(final byte[] random, final char[] characters) {
        final char[] output = new char[random.length];
        for (int i = 0; i < random.length; i++) {
            final int index = Math.abs(random[i] % characters.length);
            output[i] = characters[index];
        }
        return new String(output);
    }
}
